package com.py.credit.controller;

import java.awt.image.BufferedImage;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;
import java.util.function.Function;
import java.util.StringTokenizer;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.codec.Base64;

import cn.hutool.core.io.IORuntimeException;
import cn.hutool.core.util.CharsetUtil;
import io.jsonwebtoken.lang.Collections;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.ClientAnchor;
import org.apache.poi.ss.usermodel.Comment;
import org.apache.poi.ss.usermodel.CreationHelper;
import org.apache.poi.ss.usermodel.Drawing;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import com.py.credit.common.logs.ExceptionLogger;
import com.py.credit.common.rest.RestServiceResult;
import com.py.credit.entity.SysUser;
import com.py.credit.entity.enums.CreditMapFieldEnum;
import com.py.credit.service.CreditRepairService;
import com.py.credit.service.DissentAppealSeervice;
import com.py.credit.service.GetRoleService;
import com.py.credit.service.RemoteBaseService;
import com.py.credit.utils.DateUtils;
import com.py.credit.utils.ExcelUtil;
import com.py.credit.utils.FileUtils;
import com.py.credit.utils.UuidUtil;
import com.py.framework.core.annotation.IgnoreAuthority;
import com.py.framework.core.common.Page;
import com.py.framework.core.helper.HttpServletHelper;

/**
 * 异议申诉controller
 */
@RestController
@RequestMapping(value = "/DissentAppeal")
public class DissentAppealController extends BaseController {
	@Value("${yyclpath}")
	private String yyclpath;
	@Autowired
	private DissentAppealSeervice dissentAppealService;
	@Autowired
	private RemoteBaseService remoteBaseService;

	@Autowired
	private CreditRepairService creditRepairService;

	@Autowired
	private GetRoleService getRoleService;

	/**
	 * @api {post} /DissentAppeal/addDissent.json 添加异议申诉
	 * @apiName addDissent
	 */
	@IgnoreAuthority
	@ResponseBody
	@RequestMapping(value = "/addDissent.json")
	public RestServiceResult<Object> addDissent(HttpServletRequest request, HttpServletResponse httpResponse,
			@RequestParam(value = "condition", defaultValue = "") String condition) {
		RestServiceResult<Object> result = new RestServiceResult<>();
		try {
			Map<String, Object> parseObject = JSONObject.parseObject(condition, Map.class);
			String ztmc = parseObject.get("ztmc").toString();
			String sjlx = parseObject.get("sjlx").toString();
			String sjly = parseObject.get("sjly").toString();
			String ssnr =  String.valueOf(parseObject.get("ssnr"));
			String jbrxm = parseObject.get("jbrxm").toString();
			String jbrzjhm = parseObject.get("jbrzjhm").toString();
			String lxfs = parseObject.get("lxfs").toString();
			String txdz = parseObject.get("txdz").toString();
			String description = parseObject.get("description").toString();
			String tablename = String.valueOf(parseObject.get("tablename"));
			String record_id = String.valueOf(parseObject.get("record_id"));
			if (tablename == null || tablename.equals("null")) {
				tablename = "";
			}
			if (record_id == null || record_id.equals("null")) {
				record_id = "";
			}
			
			//正则表达式
			   String regUrl="^([hH][tT]{2}[pP]://|[hH][tT]{2}[pP][sS]://)(([A-Za-z0-9-~]+).)+([A-Za-z0-9-~\\\\/])+$";
			    Pattern p = Pattern.compile(regUrl);
			    Matcher m = p.matcher(ssnr);
			               if(!m.matches()){
			            	   ssnr = "http://"+ssnr;
					}
		
			JSONArray list = (JSONArray) (parseObject.get("files"));
			System.out.println(list);
			// String zzcl = parseObject.get("zzcl");
			// String filename = parseObject.get("filename");
			// byte[] decode = Base64.decode(zzcl, CharsetUtil.CHARSET_UTF_8);
			// getFileByBytes(decode,path,filename);
			// System.out.println(path+"/"+filename);
			String path = yyclpath;
			String filename = "";
			// 多个文件
			List filepaths = new ArrayList<>();
		
				Map<String, String> file = JSONObject.parseObject(list.get(0).toString(), Map.class);
				for (Entry<String, String> vo : file.entrySet()) {
					filename = vo.getKey();

					byte[] decode = Base64.decode(vo.getValue(), CharsetUtil.CHARSET_UTF_8);
					getFileByBytes(decode, path, filename);
					filepaths.add(path + "/" + filename);
				}
			
			
			String key = generateShortUUID();
			dissentAppealService.addDissent(ztmc, sjlx, sjly, jbrxm, jbrzjhm, lxfs, txdz, description,
					filepaths.toString(), tablename, record_id, key,ssnr);
			result.setData(key);

			return result;
		} catch (Exception e) {
			ExceptionLogger.error("DissentAppealController#addDissent", "异议申诉添加异常！ERROR:" + e.getMessage(), e);
			result.setCode(RestServiceResult.CODE_UNKNOW);
			result.setMsg("异议申诉添加异常！");
			return result;
		}
	}

	/**
	 * 通过查询码或身份证号获取异议处理的进度
	 * 
	 * @param request
	 * @param httpResponse
	 * @param condition
	 * @return
	 */
	@IgnoreAuthority
	@ResponseBody
	@RequestMapping(value = "/getProcess.json")
	public RestServiceResult<Object> getProcess(HttpServletRequest request, HttpServletResponse httpResponse,
			@RequestParam(value = "condition", defaultValue = "") String condition) {
		RestServiceResult<Object> result = new RestServiceResult<>();
		Page page = new Page();
		try {

			Map<String, String> parseObject = JSONObject.parseObject(condition, Map.class);
			page.setLimit(Integer.parseInt(String.valueOf(parseObject.get("limit"))));

			page.setPage(Integer.parseInt(String.valueOf(parseObject.get("page")))
					/ Integer.parseInt(String.valueOf(parseObject.get("limit"))) + 1);
			String cxm = parseObject.get("cxm");

			List<Map<String, String>> data = dissentAppealService.getProcessForPage(cxm, page);
			result.setData(data);
			result.setCount(page.getTotalCount());
			return result;
		} catch (Exception e) {
			ExceptionLogger.error("DissentAppealController#getProcess", "异议申诉查询进度异常！ERROR:" + e.getMessage(), e);
			result.setCode(RestServiceResult.CODE_UNKNOW);
			result.setData("查询进度异常");
			return result;
		}

	}

	/**
	 * 异议申诉列表
	 * 
	 * @param request
	 * @param httpResponse
	 * @param ztmc
	 *            主体名称
	 * @param sjly
	 *            数据来源
	 * @return
	 */

	@ResponseBody
	@RequestMapping(value = "/getTableList.json")
	public RestServiceResult<Object> getTableList(HttpServletRequest request, HttpServletResponse httpResponse,
			@RequestParam(value = "ztmc", defaultValue = "") String ztmc,
			@RequestParam(value = "sjly", defaultValue = "") String sjly, Page page) {
		RestServiceResult<Object> result = new RestServiceResult<>();
		// 获取当前用户信息
		RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
		SysUser userInfo = null;
		String rolename = "";
		String deptName = "";
		if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
			userInfo = user.getData();
			if (null == userInfo || userInfo.getId() <= 0) {

				result.setCode(RestServiceResult.CODE_UNKNOW);
				result.setMsg("系统异常，请稍后再试！");
				ExceptionLogger.error("DissentAppealController#getTableList", "未获取到当前用户信息！");
				return result;
			}
			// 获取当前用户的角色
			List<HashMap<String, Object>> rolenames = getRoleService
					.getRolesByUserId(userInfo.getId(), HttpServletHelper.getUserToken(request)).getData();
			for (Map<String, Object> map : rolenames) {
				for (String key : map.keySet()) {
					if (key.equals("roleName")) {
						if (map.get(key) != null) {
							rolename = (String) map.get(key);
						}
						break;
					}
				}
			}
		} else {
			result.setCode(user.getCode());
			result.setMsg(user.getMsg());
			return result;
		}
		if (rolename.equals("系统管理员")) {
			sjly = "";
		} else {
			sjly = userInfo.getOfficeName();
		}
		List<Map<String, String>> data = dissentAppealService.getTableListForPage(ztmc, sjly, page);
		result.setCount(page.getTotalCount());
		result.setData(data);
		return result;
	}

	/**
	 * 异议处理历史列表
	 * 
	 * @param request
	 * @param httpResponse
	 * @param ztmc
	 *            主体名称
	 * @param sjly
	 *            数据来源
	 * @return
	 */

	@ResponseBody
	@RequestMapping(value = "/getHistoryTableList.json")
	public RestServiceResult<Object> getHistoryTableList(HttpServletRequest request, HttpServletResponse httpResponse,
			@RequestParam(value = "ztmc", defaultValue = "") String ztmc,
			@RequestParam(value = "sjly", defaultValue = "") String sjly,
			@RequestParam(value = "cljg", defaultValue = "") String cljg, Page page) {
		RestServiceResult<Object> result = new RestServiceResult<>();
		// 获取当前用户信息
		RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
		SysUser userInfo = null;
		List<Map> list = new ArrayList<>();
		if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
			userInfo = user.getData();
			if (null == userInfo || userInfo.getId() <= 0) {
				result.setCode(RestServiceResult.CODE_UNKNOW);
				result.setMsg("系统异常，请稍后再试！");
				ExceptionLogger.error("DissentAppealController#getTableList", "未获取到当前用户信息！");
				return result;
			}
		} else {
			result.setCode(user.getCode());
			result.setMsg(user.getMsg());
			return result;
		}
		Long userId = userInfo.getId();
		Long deptId = userInfo.getOfficeId();
		String rolename = userInfo.getRoleName();
		List<Map<String, Object>> data  = new ArrayList<>();
		try {	
			
			if(rolename.equals("系统管理员")) {
				data = dissentAppealService.getHistoryTableListForPage(ztmc, sjly, cljg, page,null,null);
			}else if(rolename.equals("部门管理员")) {
				data = dissentAppealService.getHistoryTableListForPage(ztmc, sjly, cljg, page,deptId,null);
			}else {
				data = dissentAppealService.getHistoryTableListForPage(ztmc, sjly, cljg, page,deptId,userId);
			}
		for(int i=0;i<data.size();i++) {
			Map<String,String> title = new HashMap();
			Map<String,Object>  data1 =  new HashMap();
			Map<String,Object> resultdata = new HashMap();	
			resultdata.put("data", data.get(i));			
			String metric_name = String.valueOf(data.get(i).get("metric_name"));
			if(metric_name!=null&&!metric_name.equals("")) {
			Gson gson = new Gson();
		            /*将json格式的字符串,转换为map*/
			Map<String, Object>   res = gson.fromJson(String.valueOf(data.get(i).get("olddata")), new TypeToken<Map<String, Object>>() {
		            }.getType());
			List<String> metric = Arrays.asList((metric_name.substring(1,metric_name.length()-1)).split(","));
			// Map<Object, List<Object>> maps = metric.stream().collect(Collectors.groupingBy(Function.identity(), Collectors.toList()));
			//原始数据的字段名
			List<Map<String,String>> map1 = gson.fromJson(res.get("basedata").toString(), new TypeToken<List<Map<String,String>>>(){}.getType());
			//原始数据的参数
			Map<String,String> map2= gson.fromJson(res.get("datas").toString(), new TypeToken<Map<String,String>>(){}.getType());
			for(String key :metric) {
				for(int m=0;m<map1.size();m++) {
					if(map1.get(m).get("metric_code").equals(key.trim())) {
						title.put(key.trim(),map1.get(m).get("metric_name"));		
					}
					}
				for(String key2:map2.keySet()) {
					if(key2.equals(key.trim())) {
						data1.put(key.trim(), map2.get(key2));		
					}					
				}							
			}
			resultdata.put("title", title);
			resultdata.put("newdata", data.get(i).get("newdata"));
			resultdata.put("olddata", data1);
			}						
			
			list.add(resultdata);
		}
		
		result.setData(list);
		result.setCount(page.getTotalCount());	
		} catch (Exception e) {
			result.setMsg("获取数据失败");
			ExceptionLogger.error("DissentAppealController#getHistoryTableList", "数据异常！ERROR:" + e.getMessage(),
					e);
		}			
		return result;
	}
	

	/**
	 * 异议处理
	 * 
	 * @param bytes
	 * @param filePath
	 * @param fileName
	 */

	@ResponseBody
	@RequestMapping(value = "/DissentHandle.json")
	public RestServiceResult<Object> DissentHandle(HttpServletRequest request, HttpServletResponse httpResponse,
			@RequestParam(value = "id", defaultValue = "") String id,
			@RequestParam(value = "status", defaultValue = "") String status,
			@RequestParam(value = "record_id", defaultValue = "") String record_id,
			@RequestParam(value = "tablename", defaultValue = "") String tablename,
			@RequestParam(value = "cljg", defaultValue = "") String cljg,
			@RequestParam(value = "clyj", defaultValue = "") String clyj) {
		RestServiceResult<Object> result = new RestServiceResult<>();
		// 获取当前用户信息
		RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
		SysUser userInfo = null;
		if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
			userInfo = user.getData();
			if (null == userInfo || userInfo.getId() <= 0) {
				result.setCode(RestServiceResult.CODE_UNKNOW);
				result.setMsg("系统异常，请稍后再试！");
				ExceptionLogger.error("DissentAppealController#getTableList", "未获取到当前用户信息！");
				return result;
			}
		} else {
			result.setCode(user.getCode());
			result.setMsg(user.getMsg());
			return result;
		}
		try {
			if (tablename != null && !tablename.equals("")) {
				List listtable = StringToArrayList(tablename, ",");
				Map<String,Object> mapdata = new HashMap<>();
				List<Object> list = new ArrayList<Object>();
				for (int i = 0; i < listtable.size(); i++) {
					tablename = (String) listtable.get(i);
					if (cljg.equals("核实无误，驳回申请")) {
						dissentAppealService.DissentHandle(id, cljg, clyj, status, userInfo.getOfficeName(),"",userInfo.getOfficeId(),userInfo.getId());
					}else if (cljg.equals("信用修复")) {
						dissentAppealService.DissentHandle(id, cljg, clyj, status, userInfo.getOfficeName(),"",userInfo.getOfficeId(),userInfo.getId());
						// 修复旧数据
						creditRepairService.repair(record_id, tablename);
						/*
						 * 根据表名获取原始记录字段数据 * @param parameter1 参数1：处罚是cfSy处罚事由，黑名单是data_category数据类别
						 * 
						 * @param parameter2 参数2：处罚是cfWsh处罚文书号，黑名单是execute_refrence_no执行依据文号
						 * 
						 * @param parameter3 参数3：处罚是cfYj处罚依据，黑名单是register_date立案时间
						 */
						// 根据表名获取tableId
						Map<String, String> map = dissentAppealService
								.gettableId(tablename.substring(2, tablename.length()), record_id, tablename);
						if ("210001".equals(String.valueOf(map.get("tableId")))) {
							Map<String, String> mapcf = dissentAppealService.getmapcf(record_id, tablename);
							// 添加修复历史记录
							creditRepairService.addCreditRepairHistory(
									Integer.valueOf(String.valueOf(map.get("tableId"))), record_id, map.get("ztmc"),
									userInfo.getOfficeName(), userInfo.getUsername(), mapcf.get("CF_SY"),
									mapcf.get("CF_WSH"), mapcf.get("CF_YJ"));

						} else {
							Map<String, String> mapHei = dissentAppealService.getmapHei(record_id, tablename);
							// 添加修复历史记录
							creditRepairService.addCreditRepairHistory(
									Integer.valueOf(String.valueOf(map.get("tableId"))), record_id, map.get("ztmc"),
									userInfo.getOfficeName(), userInfo.getUsername(), mapHei.get("LRMDSY"),
									mapHei.get("RDRQ"), mapHei.get("RDYJ"));

						}
						result.setData("处理成功");

					}else if (cljg.equals("删除信息")) {
						dissentAppealService.DissentHandle(id, cljg, clyj, status, userInfo.getOfficeName(),"",userInfo.getOfficeId(),userInfo.getId());
						dissentAppealService.deleteBaseData(record_id, tablename);
						result.setData("处理成功");
						result.setMsg("处理成功");
					}else if(cljg.equals("更新信息")) {
						
						// 获取该表所有字段
						List<Map<String, String>> basedata = dissentAppealService.selectBaseData(record_id, tablename);
						// 获取该表对应的数据
						List<Map<String, Object>> datas = dissentAppealService.getdata(record_id, tablename,null,null);
						if (datas.size() > 0) {
							mapdata.put("basedata",JSON.toJSONString(basedata));
							mapdata.put("datas",JSON.toJSONString(datas.get(0)));
							list.add(basedata);
							list.add(datas);
						}
						//将原始信息保存为excel，将路径存入数据库提供下载
						dissentAppealService.DissentHandle(id, cljg, clyj, "0", userInfo.getOfficeName(),JSON.toJSONString(mapdata),userInfo.getOfficeId(),userInfo.getId());
						result.setData(list);

					}
				}
			}else {
				dissentAppealService.DissentHandle(id, cljg, clyj, status, userInfo.getOfficeName(),"",userInfo.getOfficeId(),userInfo.getId());
				result.setData("处理成功");
			}

			return result;
		} catch (Exception e) {
			result.setMsg("处理失败");
			ExceptionLogger.error("DissentAppealController#DissentHandle", "数据导处理异常！ERROR:" + e.getMessage(),
					e);
			return result;
		}

	}
	@IgnoreAuthority
	@RequestMapping(value = "/exportData.json")
	public RestServiceResult<Object> exportData(HttpServletRequest request,
			@RequestParam(value = "record_id", defaultValue = "", required = true) String record_id,
			@RequestParam(value = "tablename", defaultValue = "", required = true) String tablename,
			 HttpServletResponse response) {
		RestServiceResult<Object> result = new RestServiceResult<>();
		
		try {
			if (tablename != null && !tablename.equals("")) {
				List listtable = StringToArrayList(tablename, ",");
				List<Object> list = new ArrayList<Object>();
				for (int i = 0; i < listtable.size(); i++) {
					tablename = (String) listtable.get(i);
					// 获取该表所有字段
					List<Map<String, String>> basedata = dissentAppealService.selectBaseData(record_id, tablename);
					// 获取该表对应的数据
					List<Map<String, Object>> datas = dissentAppealService.getdata(record_id, tablename,null,null);
					if(basedata.size()>0&&datas.size()>0) {
						downloaddata(response, basedata,datas);
					}				
				}					
				}			
		} catch (Exception e) {
			result.setCode(RestServiceResult.CODE_UNKNOW);
			result.setMsg("数据导出处理异常，请稍后再试！");
			ExceptionLogger.error("DissentAppealController#exportData", "数据导出处理异常！ERROR:" + e.getMessage(),
					e);

		}
		 return result;
	}

	/**
	 * 下载文件
	 * 
	 * @param response
	 * @throws IOException
	 */
	@IgnoreAuthority
	@RequestMapping("/export.json")
	public void exportxzxkTemplate(String url, HttpServletResponse response) throws IOException {
		
		FileUtils.downloadFile(URLDecoder.decode(url, "UTF-8"), response);

	}

	// 将Byte数组转换成文件
	public static void getFileByBytes(byte[] bytes, String filePath, String fileName) {
		BufferedOutputStream bos = null;
		FileOutputStream fos = null;
		File file = null;
		try {
			File dir = new File(filePath);
			if (!dir.exists() && dir.isDirectory()) {// 判断文件目录是否存在
				dir.mkdirs();
			}
			file = new File(filePath + File.separator + fileName);
			fos = new FileOutputStream(file);
			bos = new BufferedOutputStream(fos);
			bos.write(bytes);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (bos != null) {
				try {
					bos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (fos != null) {
				try {
					fos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 * 查看数据详情
	 * 
	 * @param request
	 * @param httpResponse
	 * @param record_id
	 * @param tablename
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/Detail.json")
	public RestServiceResult<Object> Detail(HttpServletRequest request, HttpServletResponse httpResponse,
			@RequestParam(value = "record_id", defaultValue = "") String record_id,
			@RequestParam(value = "ztmc", defaultValue = "") String ztmc,
			@RequestParam(value = "tablename", defaultValue = "") String tablename) {
		RestServiceResult<Object> result = new RestServiceResult<>();
		// 获取当前用户信息
		RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
		SysUser userInfo = null;
		if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
			userInfo = user.getData();
			if (null == userInfo || userInfo.getId() <= 0) {
				result.setCode(RestServiceResult.CODE_UNKNOW);
				result.setMsg("系统异常，请稍后再试！");
				ExceptionLogger.error("DissentAppealController#getTableList", "未获取到当前用户信息！");
				return result;
			}
		} else {
			result.setCode(user.getCode());
			result.setMsg(user.getMsg());
			return result;
		}
		try {
			List listtable = StringToArrayList(tablename, ",");
			String cloumn = "";
			List<Object> list = new ArrayList<Object>();
			for (int i = 0; i < listtable.size(); i++) {
				List<Map<String, String>> basedata = dissentAppealService.selectBaseData(record_id, listtable.get(i).toString());
//				if(!basedata.isEmpty()) {
//					for(int j = 0;j<basedata.size();j++) {
//						if(basedata.get(j).get("metric_name").equals("行政相对人名称")) {
//							cloumn = basedata.get(j).get("metric_code");
//						}
//					}
//				}
				if("t_1000010010003_vVwjDLoDWy".equals(tablename)) {
					cloumn = "B000001";
				}else {
					cloumn = "A000001";
				}
				// 获取该表对应的数据
				List<Map<String, Object>> datas = dissentAppealService.getdata(record_id, listtable.get(i).toString(),ztmc,cloumn);
				if (datas.size() > 0) {
					list.add(basedata);
					list.add(datas);
				}
				result.setData(list);
			}
			return result;
		} catch (Exception e) {
			result.setMsg("查看详情失败");
			return result;
		}

	}

	/**
	 * 异议处理更新信息
	 * 
	 * @param condition
	 *            表中字段对应参数
	 * @param record_id
	 *            记录数唯一标识
	 * @param tablename
	 *            表名
	 */

	@ResponseBody
	@RequestMapping(value = "/DissentUpdateBaseData.json")
	public RestServiceResult<Object> DissentUpdateBaseData(HttpServletRequest request, HttpServletResponse httpResponse,
			@RequestParam(value = "id", defaultValue = "") String id,
			@RequestParam(value = "condition", defaultValue = "") String condition,
			@RequestParam(value = "record_id", defaultValue = "") String record_id,
			@RequestParam(value = "tablename", defaultValue = "") String tablename

	) {
		RestServiceResult<Object> result = new RestServiceResult<>();
		// 获取当前用户信息
		RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
		SysUser userInfo = null;
		if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
			userInfo = user.getData();
			if (null == userInfo || userInfo.getId() <= 0) {
				result.setCode(RestServiceResult.CODE_UNKNOW);
				result.setMsg("系统异常，请稍后再试！");
				ExceptionLogger.error("DissentAppealController#DissentUpdateBaseData", "未获取到当前用户信息！");
				return result;
			}
		} else {
			result.setCode(user.getCode());
			result.setMsg(user.getMsg());
			return result;
		}
		try {
			Set<String> categorySet = new HashSet<String>();			
			Map<String, String> parseObject = JSONObject.parseObject(condition, Map.class);
			StringBuilder builder = new StringBuilder();
			builder.append(" update ").append(tablename).append(" set ");
			if (!Collections.isEmpty(parseObject)) {

				for (String key : parseObject.keySet()) {
					if(!categorySet.contains(key)) {
						categorySet.add(key);
				}
					//if (parseObject.get(key) != null && !parseObject.get(key).equals("")) {
						builder.append(key).append(" =").append("'").append(String.valueOf(parseObject.get(key))).append("',");
					//}

				}
			}
			//获取所有类
			List<String> lists = new ArrayList<>(categorySet);
			builder.deleteCharAt(builder.length() - 1);
			builder.append(" where  record_id = ").append(record_id);
			dissentAppealService.executeDynamicSql(builder.toString());
			dissentAppealService.updateStatus(id, "1",condition,lists.toString());
			result.setMsg("修改成功");
			return result;

		} catch (Exception e) {	
			ExceptionLogger.error("DissentAppealController#DissentUpdateBaseData", "数据处理异常！ERROR:" + e.getMessage(),
					e);
			result.setMsg("处理失败");
		}

		return result;
	}
	
	

	public static ArrayList<String> StringToArrayList(String str, String separator) {
		ArrayList<String> arr = new ArrayList<String>();
		if ((str == null) || (separator == null)) {
			return arr;
		}
		StringTokenizer st = new StringTokenizer(str, separator);
		while (st.hasMoreTokens()) {
			arr.add(st.nextToken());
		}
		return arr;
	}
	
	public static void downloaddata(HttpServletResponse response, List<Map<String, String>> basedata,List<Map<String, Object>> datas) throws IOException {
		response.setContentType("application/vnd.ms-excel");
		HSSFWorkbook workbook = null;
		OutputStream fOut = null;
		
		
		// 产生工作簿对象
		workbook = new HSSFWorkbook();
		// 产生工作表对象
		HSSFSheet sheet = workbook.createSheet();
		// 得到一个poi工具
		CreationHelper factory = workbook.getCreationHelper();
		// 得到换图对象
		Drawing drawing = sheet.createDrawingPatriarch();
		// 设置注释位置
		ClientAnchor anchor = factory.createClientAnchor();
		workbook.setSheetName(0, "更新后数据");
		HSSFRow row = null;
		HSSFCell cell = null;

		// 进行转码，使其支持中文文件名
		String fileNanme = URLEncoder.encode("更新后数据", "UTF-8");
		response.setHeader("content-disposition", "attachment;filename=" + fileNanme + ".xls");
		// 创建标题行
		row = sheet.createRow(0);
		//标题行的英文名和对应下标创建一个map
		Map<String,Integer> titlemap = new HashMap<String,Integer>();
		Map<String,String> field_type = new HashMap<String,String>();

		if (!CollectionUtils.isEmpty(basedata)) {
		
			for (int i = 0; i < basedata.size(); i++) {
				sheet.setColumnWidth(i, 8000);
				cell = row.createCell(i);
				cell.setCellType(HSSFCell.CELL_TYPE_STRING);
				cell.setCellValue(basedata.get(i).get("metric_name"));
				Comment comment = drawing.createCellComment(anchor);
			
				cell.setCellComment(comment);
				titlemap.put(basedata.get(i).get("metric_code"), i);
				field_type.put(basedata.get(i).get("metric_code"),basedata.get(i).get("field_type"));
			}
			
		}		
			//写入数据	
			for (int j = 0; j < datas.size(); j++) {
				row = sheet.createRow(j + 1);// 创建一行
				//根据map的key和titlemap的key相等进行对应的列赋值
				for(Entry<String, Integer> s : titlemap.entrySet()) {
					cell=row.createCell(s.getValue());
						cell.setCellType(HSSFCell.CELL_TYPE_STRING);
						cell.setCellValue(String.valueOf(datas.get(j).get(s.getKey()))==null||String.valueOf(datas.get(j).get(s.getKey())).equals("null")?"":String.valueOf(datas.get(j).get(s.getKey())));
												
				}
		}
		fOut = response.getOutputStream();
		workbook.write(fOut);
		workbook.close();
		fOut.flush();
		fOut.close();
	}
	/**
	 * 
	 * @Title: supervisionResultList
	 * @Description: TODO(协同监管结果)
	 * @param @param request
	 * @param @param httpResponse
	 * @param @param ztmc	主体名称
	 * @param @param tybm	同意编码
	 * @param @param type	主体类型
	 * @param @param page
	 * @param @return    设定文件
	 * @return RestServiceResult<Object>    返回类型
	 * @throws
	 */
	@ResponseBody
	@RequestMapping(value = "/supervisionResultList.json")
	public RestServiceResult<Object> supervisionResultList(HttpServletRequest request, HttpServletResponse httpResponse,
			@RequestParam(value = "ztmc", defaultValue = "") String ztmc,
			@RequestParam(value = "tybm", defaultValue = "") String tybm, 
			@RequestParam(value = "type", defaultValue = "") String type,Page page) {
		RestServiceResult<Object> result = new RestServiceResult<>();
		// 获取当前用户信息
		RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
		SysUser userInfo = null;
		if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
			userInfo = user.getData();
			if (null == userInfo || userInfo.getId() <= 0) {
				result.setCode(RestServiceResult.CODE_UNKNOW);
				result.setMsg("系统异常，请稍后再试！");
				ExceptionLogger.error("DissentAppealController#getTableList", "未获取到当前用户信息！");
				return result;
			}			
		} else {
			result.setCode(user.getCode());
			result.setMsg(user.getMsg());
			return result;
		}
		List<Map<String, String>> data = dissentAppealService.getsupervisionResultListForPage(ztmc, tybm,type, page);
		result.setCount(page.getTotalCount());
		result.setData(data);
		return result;
	}
	
	@ResponseBody
	@RequestMapping(value = "/supervisionResultDetail.json")
	public RestServiceResult<Object> supervisionResultDetail(HttpServletRequest request, HttpServletResponse httpResponse,
			@RequestParam(value = "ztmc", defaultValue = "") String ztmc) {
		RestServiceResult<Object> result = new RestServiceResult<>();
		// 获取当前用户信息
		RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
		SysUser userInfo = null;
		if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
			userInfo = user.getData();
			if (null == userInfo || userInfo.getId() <= 0) {
				result.setCode(RestServiceResult.CODE_UNKNOW);
				result.setMsg("系统异常，请稍后再试！");
				ExceptionLogger.error("DissentAppealController#getTableList", "未获取到当前用户信息！");
				return result;
			}			
		} else {
			result.setCode(user.getCode());
			result.setMsg(user.getMsg());
			return result;
		}
		List<Map<String, String>> data = dissentAppealService.supervisionResultDetail(ztmc);
		
		result.setData(data);
		return result;
	}
	
	public static String[] chars = new String[] { "a", "b", "c", "d", "e", "f",
            "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s",
            "t", "u", "v", "w", "x", "y", "z", "0", "1", "2", "3", "4", "5",
            "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I",
            "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V",
            "W", "X", "Y", "Z" };


    public static String generateShortUUID() {
        StringBuffer shortBuffer = new StringBuffer();
        String uuid = UUID.randomUUID().toString().replace("-", "");
        for (int i = 0; i < 8; i++) {
            String str = uuid.substring(i * 4, i * 4 + 4);
            int x = Integer.parseInt(str, 16);
            shortBuffer.append(chars[x % 0x3E]);
        }
        return shortBuffer.toString();
    }
   
}
